<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item prop="text">
        <el-input v-model="queryParams.text" placeholder="Pls input text" clearable/>
      </el-form-item>

      <el-form-item prop="ade">
        <el-input v-model="queryParams.ade" placeholder="Pls input ade" clearable/>
      </el-form-item>

      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="Select Status" clearable>
          <el-option
            v-for="dict in dict.type.status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">Search</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">Reset</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ade:AdeKnowledge:add']"
        >New</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ade:AdeKnowledge:edit']"
        >Edit</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ade:AdeKnowledge:remove']"
        >Delete</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ade:AdeKnowledge:export']"
        >Export</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-share" size="mini" @click="handleFormat">Format</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" @click="handleImportAdeKnowledge">Import</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" @click="handleReview">Review</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="AdeKnowledgeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="ID" align="center" width="70" prop="id" />
      <el-table-column label="Suspected ADE" width="300" align="left" prop="text" show-overflow-tooltip/>
      <el-table-column label="Formated ADE" align="left" prop="ade" show-overflow-tooltip/>
      <!--
      <el-table-column label="Explain" width="200" align="left" prop="explain" show-overflow-tooltip/>
      -->
      <el-table-column label="Status" align="center" width="100" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!--
      <el-table-column label="UpdateBy" align="center" width="80" prop="updateBy" show-overflow-tooltip/>-->
       <el-table-column label="Update Time" align="center" width="140" prop="updateTime" />
       <!--
        <el-table-column label="Create Time" align="center" width="140" prop="createTime" />
        -->
      <!--<el-table-column label="Remark" align="center" prop="remark" />-->
      <el-table-column label="Actions" width="150" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ade:AdeKnowledge:edit']"
          >Edit</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ade:AdeKnowledge:remove']"
          >Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改ADE Knowledge对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="75%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" >
        <el-form-item label="Suspected ADE" prop="text">
          <el-input v-model="form.text" type="textarea" rows="2" placeholder="Pls input suspected ADE" />
        </el-form-item>
        <el-form-item label="Formated ADE" prop="ade">
          <el-input type="textarea" v-model="form.ade" :rows="15" placeholder="Pls input formated ADE"
                                @input="onJsonChange" />
          <div class="json-status mt-2">
              <el-tag :type="jsonValid ? 'success' : 'danger'" effect="plain" size="mini">
                  {{ jsonStatusText }}
              </el-tag>
          </div>
        </el-form-item>

        <el-form-item label="Explain" prop="explain">
          <el-input v-model="form.explain" type="textarea" rows="2" placeholder="Pls input explaination for non ADE" />
        </el-form-item>


        <el-form-item label="Status" prop="status">
          <el-select v-model="form.status" placeholder="Select Status">
            <el-option
              v-for="dict in dict.type.status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Remark" prop="remark">
          <el-input v-model="form.remark" type="textarea" rows="5" placeholder="Pls input Remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">OK</el-button>
        <el-button @click="cancel">Cancel</el-button>
      </div>
    </el-dialog>


    <!-- ADE Knowledge Review -->
    <el-dialog :visible.sync="showReviewDialog"   @close="showReviewDialog = false" width="80%" :title="'Review ADE Knowledge'">
      <adeknowledge-review/>
    </el-dialog>

  </div>
</template>

<script>
import { listAdeKnowledge, getAdeKnowledge, delAdeKnowledge, addAdeKnowledge, updateAdeKnowledge,startFormat,startImport } from "@/api/ade/AdeKnowledge";

import AdeknowledgeReview from "@/views/ade/adeknowledge/review.vue";

export default {
  name: "AdeKnowledge",
  dicts: ['status'],
  components: {
    AdeknowledgeReview
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // ADE Knowledge表格数据
      AdeKnowledgeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        text: null,
        ade: null,
        status: null,
      },
      // 表单参数
      form: {},

      //json相关校验
      jsonValid: true,
      jsonStatusText: 'JSON Format Correct',


      // 表单校验
      rules: {
        text: [
          { required: true, message: "Suspected ADE can not be empty", trigger: "blur" }
        ],
        ade: [
          { required: true, message: "Formated ADE can not be empty", trigger: "blur" }
        ],
        status: [
          { required: true, message: "Status can not be empty", trigger: "change" }
        ],
      },

      //ADE Knowledge Review Dialog
      showReviewDialog: false,

    };
  },
  created() {
    this.getList();
  },
  methods: {
    //打开审核页面对话框
    handleReview(){
      this.showReviewDialog = true;
    },
    handleImportAdeKnowledge() {
      this.$modal.confirm('Are you sure to import ADE Knowledge?').then(() => {
        return startImport();
      }).then(() => {
        this.$modal.msgSuccess("The import task has commenced. Please be patient and wait...");
        this.getList();
      }).catch(() => { });
    },
    //对ades结果进行规范化格式化处理
    handleFormat(){
       this.$modal.confirm('Are you sure to submit the format task?').then(() => {
        return startFormat();
      }).then(() => {
        this.$modal.msgSuccess("The format has commenced. Please be patient and wait...");
        this.getList();
      }).catch(() => { });
    },
    /** 查询ADE Knowledge列表 */
    getList() {
      this.loading = true;
      listAdeKnowledge(this.queryParams).then(response => {
        this.AdeKnowledgeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        text: null,
        ade: null,
        status: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加ADE Knowledge";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAdeKnowledge(id).then(response => {
        this.form = response.data;
        
        //格式化JSON内容
        const parsed = JSON.parse(this.form.ade || '{}');
        this.form.ade = JSON.stringify(parsed, null, 2);
        this.jsonValid = true; // 重置JSON校验状态
        this.jsonStatusText = 'JSON Format Correct';

        this.open = true;
        this.title = "Edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAdeKnowledge(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAdeKnowledge(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除ADE Knowledge编号为"' + ids + '"的数据项？').then(function() {
        return delAdeKnowledge(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ade/AdeKnowledge/export', {
        ...this.queryParams
      }, `AdeKnowledge_${new Date().getTime()}.xlsx`)
    },
    // JSON内容变化时自动验证
    onJsonChange() {
      console.log("#############")
        try {
            JSON.parse(this.form.ade);
            this.jsonValid = true;
            this.jsonStatusText = 'JSON Format Correct';
        } catch (error) {
          console.log("#############？？？wrong?")
            this.jsonValid = false;
            this.jsonStatusText = `JSON Format Wrong: ${error.message}`;
        }
    },
  }
};
</script>
